package org.edu.modules.act.service.impl;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.edu.common.api.vo.Result;
import org.edu.modules.act.service.WordOnlineService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import java.net.HttpURLConnection;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
@Service
@Transactional
public class WordOnlineServiceImpl implements WordOnlineService {
    @Override
    public  Map<String, String> getH5(String url) throws Exception{
        String[] li = url.split("/");

        String fileName = li[li.length - 1];

        long startTime = System.currentTimeMillis();
        URL wordURL = null;
        try {
            wordURL = new URL(url.trim());//转换URL
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        HttpURLConnection urlConn = (HttpURLConnection) wordURL.openConnection();//构造连接
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36");
        urlConn.connect();

        InputStream in = urlConn.getInputStream(); //获取输入流,从网站读取数据到 内存中

        //在当前项目路径下创建一个为myWord的文件夹
        File directory = new File(".");
        String path = null;
        path = directory.getCanonicalPath();

        File fi = new File(path + "\\myWord");
        if (!fi.exists()) {
            fi.mkdir();
        }

        //分割，.需要 转义
        String[] arr = fileName.split("\\.");

        Map<String, String> map = new HashMap<>();

        //如果是docx格式的话
        if (arr[1].equalsIgnoreCase("docx")) {
            System.out.println("DOCX格式的WORD文档");
            XWPFDocument document = new XWPFDocument(in);
            System.out.println("document:" + document);
            // 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
            File imageFolderFile = new File(path + "\\myWord\\");
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
            options.setExtractor(new FileImageExtractor(imageFolderFile));
            options.setIgnoreStylesIfUnused(false);
            options.setFragment(true);
            System.out.println("新文件名：" + path + "\\myWord");

            // ) 将 XWPFDocument转换成XHTML
            OutputStream out = new FileOutputStream(new File(path + "\\myWord\\" + arr[0] + ".htm"));
            document.createNumbering();
            XHTMLConverter.getInstance().convert(document, out, options);
            int len = 0;
            File f1 = new File(path + "\\myWord\\" + arr[0] + ".htm");
            InputStream in1 = null;
            try {

                in1 = new FileInputStream(f1);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte b[] = new byte[1024 * 1024];
            try {
                len = in1.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String html = new String(b, 0, len);
            String h5 = StringEscapeUtils.unescapeHtml(html);
            //关闭流
            in1.close();
            in.close();

            if (f1.exists()) {
                f1.delete();//读完删除文件
            }

//            //删减冗余的标签
//            h5=h5.replace("<span style=\"font-family:'等线';font-size:16.0pt;\">","").replace("</span>","");
//            //替换word的标记符号为 ""
//            for (int i = 1; i < 11; i++) {
//                h5 = h5.replace("{{auditOpinion"+i+"}}","");
//                h5 = h5.replace("{{auditName"+i+"}}","");
//                h5 = h5.replace("{{auditTime"+i+"}}","");
//            }
//
//            System.out.println("--------------------------------------------------------------------");
//            System.out.println(h5);

            map.put("h5", h5);
        } else {
            System.out.println("DOC格式的文档");
            HWPFDocument wordDocument = new HWPFDocument(in);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //解析word文档
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();

            File htmlFile = new File(path + "\\myWord\\" + arr[0] + ".htm");
            OutputStream outStream = new FileOutputStream(htmlFile);

            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");

            serializer.transform(domSource, streamResult);

            int len = 0;
            File f1 = new File(path + "\\myWord\\" + arr[0] + ".htm");
            InputStream in1 = null;
            try {
                in1 = new FileInputStream(f1);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte b[] = new byte[1024 * 1024];
            try {
                len = in1.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String html = new String(b, 0, len);
            String h5 = StringEscapeUtils.unescapeHtml(html);
            //先关闭流
            outStream.close();
            //关闭流
            in1.close();
            in.close();
            if (f1.exists()) {
                f1.delete();//读完删除文件
            }



//            //删减冗余的标签
//            h5=h5.replace("<span style=\"font-family:'等线';font-size:16.0pt;\">","").replace("</span>","");
//            //替换word的标记符号为 ""
//            for (int i = 1; i < 11; i++) {
//                h5 = h5.replace("{{auditOpinion"+i+"}}","");
//                h5 = h5.replace("{{auditName"+i+"}}","");
//                h5 = h5.replace("{{auditTime"+i+"}}","");
//            }

            map.put("h5", h5);
        }
        return map;
    }


}
